package com.tanhua.recommend.listener;

import com.alibaba.fastjson.JSON;
import com.tanhua.domain.mongo.PublishScore;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
@RocketMQMessageListener(topic = "tanhua-quanzi", consumerGroup = "tanhua-quanzi-group")
public class PublishScoreListener implements RocketMQListener<String> {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void onMessage(String message) {
        log.info("====接收动态消息，用于大数据推荐系统【开始】 topic：{}，消息内容：{}", "tanhua-quanzi", message);
        //接收消息，转换成Map
        Map map = JSON.parseObject(message, Map.class);
        Long userId = Long.valueOf(map.get("userId").toString());
        Long publishId = Long.valueOf(map.get("publishId").toString());
        Integer type = (Integer) map.get("type");

        //根据操作类型进行计分
        PublishScore ps = new PublishScore();
        ps.setUserId(userId);
        ps.setPublishId(publishId);
        ps.setDate(System.currentTimeMillis());
        switch (type) {
            case 1:
                ps.setScore(20D);
                break;
            case 2:
                ps.setScore(1D);
                break;
            case 3:
                ps.setScore(5D);
                break;
            case 4:
                ps.setScore(8D);
                break;
            case 5:
                ps.setScore(10D);
                break;
            case 6:
                ps.setScore(-5D);
                break;
            case 7:
                ps.setScore(-8D);
                break;
            default:
        }
        //保存到MongoDB
        mongoTemplate.save(ps);

        log.info("====接收动态消息，用于大数据推荐系统【完成】");
    }
}
